package com.baidu.process.imchat.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baidu.process.chat.core.web.bean.IMRequestServer;


import com.baidu.process.imchat.entity.ImResult;
import com.baidu.process.imchat.entity.ImchatRequest;
import com.baidu.process.imchat.service.ImChatService;
import com.baidu.process.sign.util.Constant;
import com.baidu.process.sign.util.SSLCipherSuiteUtil;
import com.baidu.process.cloud.apigateway.sdk.utils.Client;
import com.baidu.process.cloud.apigateway.sdk.utils.Request;
import okhttp3.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author:fangyuchao
 * @Description:
 * @Date: Create in 14:50 2022/11/10
 */
@Service
public class ImChatServiceImpl implements ImChatService {
    public final static String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
    public final static Locale LOCALE_US = Locale.US;
    public final static DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN, LOCALE_US);
    public final static TimeZone GMT_ZONE = TimeZone.getTimeZone("GMT+00:00");
    private static final Logger logger= LoggerFactory.getLogger(ImChatServiceImpl.class);
    @Autowired
    OkHttpClient okHttpClient;
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Value("${im.chat.url}")
    private String imChatUrl;
    @Value("${im.chat.secret}")
    private String secret;
    @Value("${im.chat.x_ca_key}")
    private String x_ca_key;


    @Override
    public ImResult imChat(IMRequestServer imRequestServer, List<Map<String,Object>> msgBody) {
        try {
            rfc1123Format.setTimeZone(GMT_ZONE);
            String channel = StringUtils.isEmpty(imRequestServer.getChannel())?"0":imRequestServer.getChannel();
            //处理请求body
        Date currentDate = new Date();
        ImchatRequest body = new ImchatRequest();
        //from与to字段与请求报文内的互相交换
        body.setFromAccount(StringUtils.isEmpty(imRequestServer.getToAccount())?"baidu":imRequestServer.getToAccount());
        body.setToAccount(imRequestServer.getFromAccount());
        body.setSessionID(imRequestServer.getSessionId());
        body.setSource(Integer.parseInt(channel));
        body.setMsgBody(msgBody);
        body.setMemberID(imRequestServer.getMemberID());
        body.setOpenID(imRequestServer.getOpenID());
        MediaType MEDIA_TYPE_JSON = MediaType.parse("application/json");
        String bodyJson= JSON.toJSONString(body);
        //构建验签用request
            Request request0 = new Request();
            request0.setKey(x_ca_key);
            request0.setSecret(secret);
            request0.setMethod("POST");
            request0.setUrl(imChatUrl);
            request0.addHeader("Content-Type", "application/json");

            request0.setBody(bodyJson);
            okhttp3.Request signedRequest = Client.signOkhttp(request0, Constant.SIGNATURE_ALGORITHM_SDK_HMAC_SHA256);
            OkHttpClient client = SSLCipherSuiteUtil.createOkHttpClient(Constant.INTERNATIONAL_PROTOCOL);
            logger.info("[sessionId:]{},向im接口发送信息报文:{}",imRequestServer.getSessionId(),bodyJson);
            Response response = client.newCall(signedRequest).execute();
            String resStr = response.toString();
        String jsonRes = response.body().string();
        logger.info("[sessionId:]{}:im接口返回结果：{}",imRequestServer.getSessionId(),resStr);
            logger.info("[sessionId:]{}:im接口返回结果2：{}",imRequestServer.getSessionId(),jsonRes);
        ImResult imResult= JSONObject.parseObject(jsonRes,ImResult.class);
        return imResult;
        }catch (Exception e){
            e.printStackTrace();
            logger.error("[sessionId:{}]调用imchat接口失败",imRequestServer.getSessionId(),e);
        }
        return null;
    }

}
